﻿using System.Reflection;
using Abp.Modules;
using Abp.Zero.EntityFramework;

namespace MyCompanyName.AbpZeroTemplate
{
    /// <summary>
    /// Entity framework module of the application.
    /// </summary>
    [DependsOn(typeof(AbpZeroEntityFrameworkModule), typeof(AbpZeroTemplateCoreModule))]
    public class AbpZeroTemplateDataModule : AbpModule
    {
        public override void PreInitialize()
        {
            //web.config (or app.config for non-web projects) file should containt a connection string named "Default".
            Configuration.DefaultNameOrConnectionString = "Default";

            DatabaseInitialize();
        }

        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
        }

        private void DatabaseInitialize()
        {
            System.Data.Entity.Database.SetInitializer(new
                MyCompanyName.AbpZeroTemplate.EntityFramework.Initializtion.CreateDatabaseInitializer());
            using (var db = new MyCompanyName.AbpZeroTemplate.EntityFramework.AbpZeroTemplateDbContext())
            {
                db.Database.Initialize(false);//只执行上面那句，不执行这句就报错【在多语句事务内不允许使用 CREATE DATABASE 语句。】
            }

            //使用数据库初始化器自动迁移                
            //System.Data.Entity.Database.SetInitializer(new
            //    System.Data.Entity.MigrateDatabaseToLatestVersion<MyCompanyName.AbpZeroTemplate.EntityFramework.AbpZeroTemplateDbContext,
            //        MyCompanyName.AbpZeroTemplate.Migrations.Configuration>());
            //                                   Migrations.Configuration.cs  >>   this.AutomaticMigrationsEnabled = true;//需要开启自动迁移
            //Migrations文件夹已经排除，上面的代码未测试。后期稍稳定，线上的生产环境 升级时 可以用这种方法自动生成sql 

        }

    }
}
